package com.mq.consumer.test;

import com.mq.common.Object2ByteArrayUtils;
import com.rabbitmq.client.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description
 * @date 2019/8/16
 */
public class ConsumerFanout {


    public static void main(String[] args) {

        try {
            ConnectionFactory connectionFactory = new ConnectionFactory();

            connectionFactory.setUsername("zhanghaidong");
            connectionFactory.setPassword("mqzhd123");
            connectionFactory.setVirtualHost("/");
            connectionFactory.setHost("127.0.0.1");
            connectionFactory.setPort(5672);
            Connection connection = connectionFactory.newConnection("fanout测试");

            Channel channel = connection.createChannel();

            channel.exchangeDeclare("fanout-exchange",
                    BuiltinExchangeType.FANOUT,
                    false,
                    false,
                    false,
                    null);

            channel.queueDeclare("fanout-queue", false, false, false, null);

            channel.queueBind("fanout-queue", "fanout-exchange", "fanout-routingKey", null);

            channel.basicConsume("fanout-queue", true, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String key = envelope.getRoutingKey();
                    Map<String, Object> map = convert(body);
                    long deliveryTag = envelope.getDeliveryTag();
                    System.out.println("routingKey = " + key + " ; message = " + map.toString() + " ; deliveryTag = " + deliveryTag);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Map<String, Object> convert(byte[] bytes) {

        ByteArrayInputStream byteInt=new ByteArrayInputStream(bytes);
        ObjectInputStream objInt= null;
        try {
            objInt = new ObjectInputStream(byteInt);
            Object o = objInt.readObject();
            return (Map<String, Object>) o;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<>(2);
    }

}
